package com.ee.chat.api.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ee.chat.api.common.CommonService;
import com.ee.chat.api.service.IVipService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.*;
import com.ee.chat.common.service.IPayService;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class VipServiceImpl implements IVipService {
    @Value("${spring.profiles.active}")
    String active;

    @Resource
    VipConfigMapper vipConfigMapper;
    @Resource
    CommonService commonService;
    @Resource
    UserVipMapper userVipMapper;
    @Resource
    UserVipLogMapper userVipLogMapper;
    @Resource
    SysOrderMapper sysOrderMapper;
    @Resource
    IPayService payService;
    @Resource
    UserMapper userMapper;

    @Override
    public Result getVipPackages(String token, Integer type) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);

        //返回android套餐
        List<Map<String, Object>> vips = vipConfigMapper.getVips(type);
        for(Map<String, Object> vip : vips){
            Integer validMonth = Integer.parseInt(vip.get("validMonth").toString());
            if(validMonth >= 100) {
                vip.put("validMonth", "终身");
            }else{
                vip.put("validMonth", validMonth+"个月");
            }
            List<Map> details = JSONArray.parseArray(vip.get("details")+"", Map.class);
            vip.put("details", details);
        }

        UserVip userVip = userVipMapper.getByUserId(userId);
        Map<String, Object> vip = new HashMap<>();
        if(userVip != null && userVip.getEndTime().isAfter(LocalDateTime.now())){
            VipConfig vipConfig = vipConfigMapper.selectByIdentity(userVip.getIdentity());

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            vip.put("endTime", formatter.format(userVip.getEndTime()));
            vip.put("identity", userVip.getIdentity());
            String details = vipConfigMapper.selectByIdentity(userVip.getIdentity()).getDetails();
            vip.put("details", JSONObject.parseObject(details, List.class));

            long useDay = DateUtil.getDateDiffDay(DateUtil.parse(formatter.format(userVip.getBeginTime())), new Date());
            vip.put("useDay", useDay);
            double saveAmount = new BigDecimal(vipConfig.getSaveAmount()+"")
                    .divide(new BigDecimal(100+""), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
            vip.put("saveAmount", saveAmount);
        }else{
            vip.put("identity", 0); //不是会员
        }
        User user = userMapper.selectById(userId);
        vip.put("name", user.getName());
        vip.put("icon", user.getIcon());

        data.put("vips", vips);
        data.put("vip", vip);

        //获取支付渠道
        Map<String, Object> pay = payService.getPayStatus(userId);
        data.put("pay", pay);

        return Result.returnSuccess(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result buyVip(String token, Integer vipId, Integer payWay) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);

        VipConfig vipConfig = vipConfigMapper.selectById(vipId);
        if(vipConfig == null){
            return Result.returnFailure("套餐不存在");
        }

        String orderNumber = StringUtil.getOrderNumber();

        //添加会员购买记录
        UserVipLog userVipLog = new UserVipLog(userId, vipId, payWay, vipConfig.getAmount(), orderNumber, 0);
        userVipLogMapper.insert(userVipLog);

        //统一下单
//        int random = 0;
//        if("prod".equals(active)){
//            random = (int)(Math.random() * 20);
//        }
//        Integer undulateAmount = vipConfig.getAmount() - random;
        PayChannelConfig payChannelConfig = payService.getPayConfig(userId, payWay);
        data = payService.orderHandle(userId, null, payChannelConfig.getId(), vipConfig.getAmount(), orderNumber, "充值投诉与客服微信：ppjiyou");
        data.put("payPattern", 0);  //原生支付
        if(payChannelConfig.getType() != 0){
            data.put("payPattern", 1);  //H5拉起支付
        }

        //添加系统订单
        SysOrder sysOrder = new SysOrder(userId, orderNumber, payWay, null, payChannelConfig.getId(), vipConfig.getAmount(), 0, 2, 0);
        sysOrderMapper.insert(sysOrder);

        return Result.returnSuccess(data);
    }
}
